package com.sj.hh.ui.patient;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.AppCompatEditText;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.model.Response;
import com.mbt.deal.util.ToastUtil;
import com.rong.mbt.personal.bean.order.OrderPublishBean;
import com.rong.mbt.personal.bean.order.PushOrderFeedBean;
import com.rong.mbt.personal.http.OkHttpManager;
import com.rong.mbt.personal.http.UrlApi;
import com.rong.mbt.personal.http.callback.JsonCallback;
import com.rong.mbt.personal.utils.SpUtils;
import com.sj.friendcircle.common.router.RouterList;
import com.sj.friendcircle.lib.entity.ImageInfo;
import com.sj.friendcircle.lib.helper.AppFileHelper;
import com.sj.friendcircle.lib.helper.PermissionHelper;
import com.sj.friendcircle.lib.interfaces.OnPermissionGrantListener;
import com.sj.friendcircle.lib.manager.compress.CompressManager;
import com.sj.friendcircle.lib.manager.compress.OnCompressListener;
import com.sj.friendcircle.lib.utils.ToolUtil;
import com.sj.friendcircle.ui.helper.PhotoHelper;
import com.sj.friendcircle.ui.imageloader.ImageLoadMnanger;
import com.sj.friendcircle.ui.util.UIHelper;
import com.sj.friendcircle.ui.widget.imageview.PreviewImageView;
import com.sj.friendcircle.ui.widget.popup.PopupProgress;
import com.sj.friendcircle.ui.widget.popup.SelectPhotoMenuPopup;
import com.sj.hh.R;
import com.sj.hh.ui.ActivityLauncher;
import com.sj.hh.widget.ClearEditText;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.rongcloud.im.server.entity.PickerType;
import cn.rongcloud.im.ui.activity.base.BaseActivity;
import cn.rongcloud.im.ui.widget.switchbutton.SwitchButton;

/**
 * 发布订单
 */
@Route(path = RouterList.OrderPreActivity.path)
@SuppressLint("NewApi")
public class OrderPreActivity extends BaseActivity {


    @BindView(R.id.ll_navigation_bar_left_back)
    LinearLayout llNavigationBarLeftBack;
    @BindView(R.id.tv_navigation_bar_center)
    TextView tvNavigationBarCenter;
    @BindView(R.id.tv_order_type)
    TextView tvOrderType;
    @BindView(R.id.ll_order_type)
    LinearLayout llOrderType;
    @BindView(R.id.tv_verification_code)
    TextView tvVerificationCode;
    @BindView(R.id.edit_feed)
    TextView editFeed;
    @BindView(R.id.tv_health_time)
    TextView tvHealthTime;
    @BindView(R.id.ll_health_time)
    LinearLayout llHealthTime;
    @BindView(R.id.edit_age)
    AppCompatEditText editAge;
    @BindView(R.id.switch_button)
    SwitchButton switchButton;
    @BindView(R.id.edit_vcode)
    ClearEditText editVcode;
    @BindView(R.id.id_editor_detail_font_count)
    TextView idEditorDetailFontCount;
    @BindView(R.id.order_pre_img_add)
    ImageView orderPreImgAdd;
    @BindView(R.id.preview_image_content)
    PreviewImageView previewImageContent;
    @BindView(R.id.id_order_pre_img)
    TextView idOrderPreImg;
    @BindView(R.id.checkbox)
    CheckBox checkbox;
    @BindView(R.id.ll_register_protocol)
    LinearLayout llRegisterProtocol;
    @BindView(R.id.submit)
    Button submit;
    @BindView(R.id.ll_feed)
    LinearLayout llFeed;


    private SelectPhotoMenuPopup mSelectPhotoMenuPopup;
    private PermissionHelper permissionHelper;
    private PopupProgress mPopupProgress;
    private List<ImageInfo> selectedPhotos = new ArrayList<>();
    private List<PickerType> pikerType;
    private List<PickerType> feeds = new ArrayList<>();
    private List<PickerType> healthTimes = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order_pre);
        ButterKnife.bind(this);

        mTitle.setText("发布订单");

        pikerType = new ArrayList<>();
        pikerType.add(new PickerType("0", "普通订单"));
        pikerType.add(new PickerType("1", "健康管理订单"));

        AppFileHelper.initStroagePath(this);
        permissionHelper = new PermissionHelper(this);

        initListener();
    }

    private void initListener() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            previewImageContent.setOnAddPhotoClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    permissionHelper.requestPermission(new OnPermissionGrantListener() {
                        @Override
                        public void onPermissionGranted(PermissionHelper.Permission... grantedPermissions) {
                            showSelectPhotoPopup();
                        }

                        @Override
                        public void onPermissionsDenied(PermissionHelper.Permission... deniedPermissions) {

                        }
                    }, PermissionHelper.Permission.WRITE_EXTERNAL_STORAGE, PermissionHelper.Permission.READ_EXTERNAL_STORAGE);
                }
            });

            previewImageContent.setDatas(selectedPhotos, new PreviewImageView.OnLoadPhotoListener<ImageInfo>() {
                @Override
                public void onPhotoLoading(int pos, ImageInfo data, @NonNull ImageView imageView) {
                    ImageLoadMnanger.INSTANCE.loadImage(imageView, data.getImagePath());
                }
            });
        }
    }

    private void showSelectPhotoPopup() {
        if (mSelectPhotoMenuPopup == null) {
            mSelectPhotoMenuPopup = new SelectPhotoMenuPopup(this);
            mSelectPhotoMenuPopup.setOnSelectPhotoMenuClickListener(new SelectPhotoMenuPopup.OnSelectPhotoMenuClickListener() {
                @Override
                public void onShootClick() {
                    PhotoHelper.fromCamera(OrderPreActivity.this, false);
                }

                @Override
                public void onAlbumClick() {
                    ActivityLauncher.startToPhotoSelectActivity(OrderPreActivity.this, RouterList.FriendCircleBg.requestCode);
                }
            });
        }
        mSelectPhotoMenuPopup.showPopupWindow();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == RouterList.FriendCircleBg.requestCode && resultCode == RESULT_OK) {
            List<ImageInfo> result = data.getParcelableArrayListExtra(RouterList.PhotoSelectActivity.key_result);
            if (result != null) {
                previewImageContent.addData(result);
            }
//            refreshTitleRightClickable();
        }else {
            PhotoHelper.handleActivityResult(this, requestCode, resultCode, data, new PhotoHelper.PhotoCallback() {
                @Override
                public void onFinish(String filePath) {
                    List<ImageInfo> selectedPhotos = new ArrayList<ImageInfo>();
                    selectedPhotos.add(new ImageInfo(filePath, null, null, 0, 0));
                    if (selectedPhotos != null) {
                        previewImageContent.addData(selectedPhotos);
                    }
//                    if (requestCode == RouterList.FriendCircleBg.REQUEST_FROM_CAMERA_BG) {
//                        uploadBackgroundImageFile(selectedPhotos);
//                    } else {
//                        ActivityLauncher.startToPublishActivityWithResult(FriendCircleActivity.this,
//                                RouterList.PublishActivity.MODE_MULTI,
//                                selectedPhotos,
//                                RouterList.PublishActivity.requestCode);
//                    }
                }

                @Override
                public void onError(String msg) {
                    UIHelper.ToastMessage(msg);
                }
            });
        }
    }


    @OnClick({R.id.ll_order_type, R.id.submit, R.id.ll_health_time, R.id.ll_feed})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_order_type://订单类型（一个选择框：0：普通订单  1：健康管理订单）
                showPickerView(pikerType, new OnOptionsSelectListener() {
                    @Override
                    public void onOptionsSelect(int options1, int options2, int options3, View v) {
                        tvOrderType.setText(pikerType.get(options1).getValue());
//                        oderType = pikerType.get(options1).getId();
                        if (options1 == 0) {
                            llHealthTime.setVisibility(View.GONE);
                            getDictionary("baseorderfeed");//普通订单
                        } else {
                            llHealthTime.setVisibility(View.VISIBLE);
                            getDictionary("healthorderfeed");//健康订单
                            getDictionary("healthtime");//健康时间
                        }
                    }
                });
                break;
            case R.id.ll_health_time:
                showPickerView(healthTimes, new OnOptionsSelectListener() {
                    @Override
                    public void onOptionsSelect(int options1, int options2, int options3, View v) {
                        tvHealthTime.setText(healthTimes.get(options1).getValue());
//                        healthTime = healthTimes.get(options1).getId();
                    }
                });
                break;
            case R.id.ll_feed:
                showPickerView(feeds, new OnOptionsSelectListener() {
                    @Override
                    public void onOptionsSelect(int options1, int options2, int options3, View v) {
                        editFeed.setText(feeds.get(options1).getValue());
                    }
                });
                break;
            case R.id.submit:
                List<ImageInfo> datas = previewImageContent.getDatas();
                final boolean hasImage = !ToolUtil.isListEmpty(datas);
                if (mPopupProgress == null) {
                    mPopupProgress = new PopupProgress(this);
                }
                String[] uploadTaskPaths;
                if (hasImage) {
                    uploadTaskPaths = new String[datas.size()];
                    for (int i = 0; i < datas.size(); i++) {
                        uploadTaskPaths[i] = datas.get(i).getImagePath();
                    }
                    doCompress(uploadTaskPaths, new OnCompressListener.OnCompressListenerAdapter() {
                        @Override
                        public void onSuccess(List<String> imagePath) {
                            if (!ToolUtil.isListEmpty(imagePath)) {
                                ArrayList<File> files = new ArrayList<>();
                                for (int i = 0; i < imagePath.size(); i++) {
                                    uploadTaskPaths[i] = imagePath.get(i);
                                    File file = new File(imagePath.get(i));
                                    files.add(file);
                                }
                                publishOrdersImage(files);
                            } else {
                                publishOrders();
                            }
                        }
                    });
                } else {
                    publishOrders();
                }
                break;
        }
    }

    /**
     * 费用类型
     *
     * @param name
     */
    private void getDictionary(String name) {
        HttpParams params = OkHttpManager.getParams();
        params.put("name", name);
        OkHttpManager.getInstance(this).get(UrlApi.dictionaryFind, params, new JsonCallback<PushOrderFeedBean>() {
            @Override
            public void onSuccess(Response<PushOrderFeedBean> response) {
                if (response != null && response.body() != null) {
                    if ("healthtime".equals(name)) {
                        for (PushOrderFeedBean.DataBean.ListBean bean : response.body().getData().getList()) {
                            PickerType pickerType = new PickerType();
                            pickerType.setId(bean.getId() + "");
                            pickerType.setValue(bean.getValue());
                            healthTimes.add(pickerType);
                        }
                        if (healthTimes.size() > 0) {
                            tvHealthTime.setText(healthTimes.get(0).getValue());
                        }
                    } else {
                        for (PushOrderFeedBean.DataBean.ListBean bean : response.body().getData().getList()) {
                            PickerType pickerType = new PickerType();
                            pickerType.setId(bean.getId() + "");
                            pickerType.setValue(bean.getValue());
                            feeds.add(pickerType);
                        }
                        if (feeds.size() > 0) {
                            editFeed.setText(feeds.get(0).getValue());
                        }
                    }
                }
            }
        });
    }


    private void publishOrdersImage(ArrayList<File> file) {
        String feed = editFeed.getText().toString().trim();
        if (TextUtils.isEmpty(feed)) feed = "2";
        String content = editVcode.getText().toString().trim();
        String age = editAge.getText().toString().trim();
        int sex = 1;
        if (switchButton.isChecked()) {
            sex = 2;
        } else {
            sex = 1;
        }
        String oderType = tvOrderType.getText().toString().trim();
        String healthTime = tvHealthTime.getText().toString().trim();

        OkGo.<OrderPublishBean>post(UrlApi.orderPreUploadOrderImg)
                .tag(this)
                .isMultipart(true)
                .headers("mbtToken", SpUtils.getToken(this))
                .params("feed", feed)
                .params("title", "")
                .params("content", content)
                .params("sex", sex)
                .params("type", oderType)//订单类型  0：普通订单  1：健康管理订单
                .params("healthTime", healthTime)//健康时间
                .params("age", age)
                .addFileParams("file", file)
                .execute(new JsonCallback<OrderPublishBean>() {
                    @Override
                    public void onSuccess(Response<OrderPublishBean> response) {
                        if (response != null && response.body() != null) {
                            int resultCode = response.body().getResultCode();
                            if (resultCode == 0) {
                                ToastUtil.makeToast(mContext, "订单发布成功！");
                                finish();
                            } else {
                                ToastUtil.makeToast(mContext, "订单发布失败！");
                            }
                        }
                    }
                });
    }

    private void publishOrders() {
        String feed = editFeed.getText().toString().trim();
        if (TextUtils.isEmpty(feed)) feed = "2";
        String content = editVcode.getText().toString().trim();
        String age = editAge.getText().toString().trim();
        int sex = 1;
        if (switchButton.isChecked()) {
            sex = 2;
        } else {
            sex = 1;
        }
        String oderType = tvOrderType.getText().toString().trim();
        String healthTime = tvHealthTime.getText().toString().trim();

        OkGo.<OrderPublishBean>get(UrlApi.orderPreInsert)
                .tag(this)
                .headers("mbtToken", SpUtils.getToken(this))
                .params("feed", feed)
                .params("title", "")
                .params("content", content)
                .params("sex", sex)
                .params("type", oderType)//订单类型  0：普通订单  1：健康管理订单
                .params("healthTime", healthTime)//健康时间
                .params("age", age)
                .execute(new JsonCallback<OrderPublishBean>() {
                    @Override
                    public void onSuccess(Response<OrderPublishBean> response) {
                        if (response != null && response.body() != null) {
                            int resultCode = response.body().getResultCode();
                            if (resultCode == 0) {
                                ToastUtil.makeToast(mContext, "订单发布成功！");
                                finish();
                            } else {
                                ToastUtil.makeToast(mContext, "订单发布失败！");
                            }
                        }
                    }
                });
    }

    private void doCompress(String[] uploadPaths, final OnCompressListener.OnCompressListenerAdapter listener) {
        CompressManager compressManager = CompressManager.create(this);
        for (String uploadPath : uploadPaths) {
            compressManager.addTask().setOriginalImagePath(uploadPath);
        }
        mPopupProgress.showPopupWindow();
        compressManager.start(new OnCompressListener.OnCompressListenerAdapter() {
            @Override
            public void onSuccess(List<String> imagePath) {
                if (listener != null) {
                    listener.onSuccess(imagePath);
                }
                mPopupProgress.dismiss();
            }

            @Override
            public void onCompress(long current, long target) {
                float progress = (float) current / target;
                mPopupProgress.setProgressTips("正在压缩第" + current + "/" + target + "张图片");
                mPopupProgress.setProgress((int) (progress * 100));
            }

            @Override
            public void onError(String tag) {
                mPopupProgress.dismiss();
                UIHelper.ToastMessage(tag);
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (permissionHelper != null)
            permissionHelper.handleDestroy();
    }
}
